package com.cain.calendar.activity;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.cain.calendar.R;
import com.cain.calendar.bean.Event;
import com.cain.calendar.dao.CalendarDAO;
import com.cain.calendar.receiver.OneShotAlarm;
import com.cain.calendar.tool.Constant;
import com.cain.calendar.view.CustomDialog;

import java.util.Calendar;
import java.util.Date;

public class EditActivity extends AppCompatActivity {

    private EditText nameEdit;
    private TextView dateText;
    private TextView timeText;
    private TextView tagText;
    private EditText remarkEdit;

    private Event event;

    public static final int RESULT_CODE_UPDATE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        event = (Event) getIntent().getSerializableExtra("event");
        if (event == null)
            event = new Event();

        setContentView(R.layout.activity_edit);
        nameEdit = (EditText) findViewById(R.id.edit_name);
        dateText = (TextView) findViewById(R.id.edit_date);
        timeText = (TextView) findViewById(R.id.edit_time);
        tagText = (TextView) findViewById(R.id.edit_tag);
        remarkEdit = (EditText) findViewById(R.id.edit_remark);

        nameEdit.setText(event.getName());
        Date date = event.getTime();
        dateText.setText(String.format("%04d/%02d/%02d %s",
                date.getYear() + 1900,
                date.getMonth() + 1,
                date.getDate(),
                Constant.weekdayName[date.getDay()]));
        timeText.setText(String.format("%02d:%02d", date.getHours(), date.getMinutes()));
        tagText.setText(event.getTag());
        remarkEdit.setText(event.getRemark());
    }

    /**
     * 设置日期
     * @param view
     */
    public void setDate(View view) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View content = inflater.inflate(R.layout.date_picker, null);
        final DatePicker picker = (DatePicker) content.findViewById(R.id.date_picker);
        Date date = event.getTime();
        picker.updateDate(date.getYear() + 1900, date.getMonth(), date.getDate());

        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setTitle("选择日期");
        builder.setContentView(content);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                int year = picker.getYear();
                int month = picker.getMonth();
                int day = picker.getDayOfMonth();
                Date date = event.getTime();
                date.setYear(year - 1900);
                date.setMonth(month);
                date.setDate(day);
                dateText.setText(String.format("%04d/%02d/%02d %s",
                        date.getYear() + 1900,
                        date.getMonth() + 1,
                        date.getDate(),
                        Constant.weekdayName[date.getDay()]));
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        CustomDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    /**
     * 设置时间
     * @param view
     */
    public void setTime(View view) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View content = inflater.inflate(R.layout.time_picker, null);
        final TimePicker picker = (TimePicker) content.findViewById(R.id.time_picker);
        Date date = event.getTime();
        picker.setCurrentHour(date.getHours());
        picker.setCurrentMinute(date.getMinutes());

        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setTitle("选择时间");
        builder.setContentView(content);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                int hour = picker.getCurrentHour();
                int minute = picker.getCurrentMinute();
                Date date = event.getTime();
                date.setHours(hour);
                date.setMinutes(minute);
                timeText.setText(String.format("%02d:%02d", date.getHours(), date.getMinutes()));
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        CustomDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    /**
     * 设置标签
     * @param view
     */
    public void setTag(View view) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View content = inflater.inflate(R.layout.tag_picker, null);
        LinearLayout panel = (LinearLayout) content.findViewById(R.id.tag_picker_panel);

        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setTitle("选择标签");
        builder.setContentView(content);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        final CustomDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);

        View.OnClickListener tagOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int id = Integer.parseInt(v.getTag().toString());
                if (id >= 0) {
                    String tag = Constant.tagList.get(id);
                    event.setTag(tag);
                    tagText.setText(tag);
                    dialog.dismiss();
                } else {
                    dialog.dismiss();
                    editTag();
                }
            }
        };
        int childCount = panel.getChildCount();
        for (int i = 0; i < childCount; ++i) {
            View v = panel.getChildAt(i);
            v.setOnClickListener(tagOnClickListener);
        }

        dialog.show();
    }

    /**
     * 自定义标签
     */
    private void editTag() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View content = inflater.inflate(R.layout.tag_edit, null);
        final EditText editText = (EditText) content.findViewById(R.id.tag_edit_text);

        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setTitle("自定义标签");
        builder.setContentView(content);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String tag = editText.getText().toString().trim();
                if (tag.length() == 0)
                    Toast.makeText(EditActivity.this, "请输入标签名", Toast.LENGTH_SHORT).show();
                else {
                    event.setTag(tag);
                    tagText.setText(tag);
                    dialog.dismiss();
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        CustomDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    /**
     * 保存日程
     * @param view
     */
    public void save(View view) {
        String name = nameEdit.getText().toString().trim();
        if (name.length() == 0) {
            Toast.makeText(this, "请输入日程名称", Toast.LENGTH_SHORT).show();
            return;
        }
        String remark = remarkEdit.getText().toString().trim();
        event.setName(name);
        event.setRemark(remark);
        if (event.getId() == -1)
            CalendarDAO.insertEvent(event);
        else
            CalendarDAO.updateEvent(event);

        Intent intent = new Intent(this, OneShotAlarm.class);
        intent.putExtra("event", event);
        PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);

        Calendar calendar = Calendar.getInstance();
        Date date = event.getTime();
        calendar.set(date.getYear() + 1900, date.getMonth(), date.getDay(), date.getHours(), date.getMinutes());

        AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
        am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);

        setResult(RESULT_CODE_UPDATE);
        finish();
    }

    /**
     * 返回
     * @param view
     */
    public void back(View view) {
        finish();
    }
}
